package com.test.resumeanalysis.util

import android.annotation.SuppressLint
import android.content.Context
import android.net.Uri
import android.provider.OpenableColumns
import android.util.Base64
import com.itextpdf.text.Document
import com.itextpdf.text.Paragraph
import com.itextpdf.text.pdf.PdfWriter
import com.setruth.mvvmbaseproject.util.LogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.apache.poi.xwpf.usermodel.XWPFDocument
import java.util.zip.ZipInputStream

import java.io.*
import java.util.zip.ZipEntry

import java.io.File
import java.io.FileInputStream
import java.io.IOException

object FileUtil {
    suspend fun createTxtFile(filePath: String, content: String) {
        val file = File(filePath)
        try {
            val fileWriter = FileWriter(file)
            fileWriter.write(content)
            fileWriter.close()

        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    suspend fun jpgToBase64(filePath: String):String{
        val file = File(filePath)
        val bytes = ByteArray(file.length().toInt())
        try {
            val inputStream = FileInputStream(file)
            inputStream.read(bytes)
            inputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        var base64 = "data:image/jpeg;base64,"+Base64.encodeToString(bytes, Base64.DEFAULT)

        base64=base64.replace("\\n","")
        return base64.trim().replace("\\s+".toRegex(), "")
    }

    suspend fun  filetoBase64(filePath: String): String {
        val file = File(filePath)
        val bytes = ByteArray(file.length().toInt())
        try {
            val inputStream = FileInputStream(file)
            inputStream.read(bytes)
            inputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        var base64 = "data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,"+Base64.encodeToString(bytes, Base64.DEFAULT)

        base64=base64.replace("\\n","")
        return base64.trim().replace("\\s+".toRegex(), "")

    }
//   suspend fun convertDocxToBase64(inputFile: File): String {
//
//           val inputStream = FileInputStream(inputFile)
//           val zipInputStream = ZipInputStream(inputStream)
//           var entry: ZipEntry? = zipInputStream.nextEntry
//           while (entry != null && entry.name != "word/document.xml") {
//               entry = zipInputStream.nextEntry
//           }
//           val outputStream = ByteArrayOutputStream()
//           val buffer = ByteArray(1024)
//           var length: Int
//           while (zipInputStream.read(buffer).also { length = it } >= 0) {
//               outputStream.write(buffer, 0, length)
//           }
//           val bytes = outputStream.toByteArray()
//           return Base64.encodeBase64String(bytes)
//       }
//    suspend fun fileToBase64(filePath: String): String {
//        val file = File(filePath)
//        val bytes = Files.readAllBytes(file.toPath())
//        return Base64.getEncoder().encodeToString(bytes)
//    }
    @SuppressLint("Range")
    fun getFileRealPath(context: Context, uri: Uri?): String? {
        var realPath: String? = null
        uri?.let { uri ->
            val contentResolver = context.contentResolver
            val cursor = contentResolver.query(uri, null, null, null, null)
            cursor?.use { cursor ->
                if (cursor.moveToFirst()) {
                    val displayName =
                        cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    val inputStream = contentResolver.openFileDescriptor(uri, "r")?.fileDescriptor?.let {
                        FileInputStream(it)
                    }
                    val file = context.cacheDir.resolve(displayName)
                    inputStream?.use { input ->
                        FileOutputStream(file).use { output ->
                            val buffer = ByteArray(4 * 1024) // or other buffer size
                            var read: Int
                            while (input.read(buffer).also { read = it } != -1) {
                                output.write(buffer, 0, read)
                            }
                            output.flush()
                        }
                    }
                    realPath = file.absolutePath
                }
            }
        }
        return realPath
    }

//
//suspend fun convertDocxToPdf(docxFile: File, pdfFile: File) {
//
//        val docx = XWPFDocument(withContext(Dispatchers.IO) {
//            FileInputStream(docxFile)
//        })
//        val pdf = Document()
//        PdfWriter.getInstance(pdf, FileOutputStream(pdfFile))
//        pdf.open()
//        for (paragraph in docx.paragraphs) {
//            pdf.add(Paragraph(paragraph.text))
//        }
//        pdf.close()
//
//    }
//
//
//    fun convertDocxToPdf(docxFilePath: String, pdfFilePath: String) {
//        try {
//            val docxFile = File(docxFilePath)
//            val pdfFile = File(pdfFilePath)
//
//            // 读取 docx 文件
//            val fis = FileInputStream(docxFile)
//            val document = XWPFDocument(fis)
//
//            // 创建 PDF 文件
//            val fos = FileOutputStream(pdfFile)
//            val pdfDoc = Document()
//            PdfWriter.getInstance(pdfDoc, fos)
//
//            // 将 docx 文件内容写入 PDF 文件中
//            pdfDoc.open()
//            for (paragraph in document.paragraphs) {
//                val text = paragraph.text
//                pdfDoc.add(Paragraph(text))
//            }
//            pdfDoc.close()
//
//            // 关闭输入输出流
//            fis.close()
//            fos.close()
//
//            LogUtil.e("PDF Converter"+"Docx to PDF conversion succeeded!")
//        } catch (e: Exception) {
//            LogUtil.e("PDF Converter"+"Docx to PDF conversion failed: ${e.message}")
//        }
//    }

}